/*
  学习目标：websocket的基本使用
  1. 下包 socket.io-client
  4. 发送消息
  5. 接收消息
  6. 关闭连接
*/

import { useEffect } from "react";
import { io } from "socket.io-client";
import styles from "./index.module.scss";
import { getAuth } from "./../../utils/storage";
import { Button } from "antd-mobile";
import history from "@/utils/history";

export default function Test() {
  useEffect(() => {
    // 2. 创建客户端实例 - 参考后台给的文档
    const client = io("http://geek.itheima.net", {
      query: {
        token: getAuth().token,
      },
      transports: ["websocket"],
    });

    // 3. 监听连接成功
    client.on("connect", () => {
      console.log("连接成功  ----->  ");
    });

    client.emit("message", { msg: "吃了没", timestamp: Date.now() });

    client.on("message", (data) => {
      console.log("data  ----->  ", data);
    });

    return () => {
      client.close();
    };
  }, []);

  return (
    <div className={styles.root}>
      <Button onClick={() => history.push("/")}>点我</Button>
    </div>
  );
}
